package cn.edu.scau.cmi.front.controller;

import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiHibernateProxyUtil;
import cn.edu.scau.cmi.ema.util.CmiSetUtil;
import cn.edu.scau.cmi.ema.util.CmiTimeUtil;
import cn.edu.scau.cmi.front.domain.AddressWrap;
import cn.edu.scau.cmi.front.domain.FrontEventPagination;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.util.*;

@Controller("FrontEventController")
public class FrontEventController extends FrontCmiEmaController {
	
	
	private String toBeDeleteEventDescription = "该事件经过审核是无效事件，待后期清理";
	
	
	@RequestMapping(value = "/shenEvent", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void shenEvent() throws Throwable {
		 Workbook wb=new XSSFWorkbook();

	    FileOutputStream fos = new FileOutputStream(new File("E:\\临时文件目录\\粮事件.xlsx"));
	    Sheet sheet = wb.createSheet("shen");
		
		
		Set<Event> events = eventDAO.findAllEvents();
		int i=1;
		for (Iterator iterator = events.iterator(); iterator.hasNext();) {
			Event event = (Event) iterator.next();
			//			ema-grainAndOil=562,825,826,827,828,900,901,902,903,904,905,906,907,908,909,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257
//			idSet = [1, 2];
//			醋和酱油
			Integer[] grainIdList = {562,825,826,827,828,900,901,902,903,904,905,906,907,908,909,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257};
			Set<Integer> idSet = new HashSet<Integer>();
			Integer[] oilIdList = {563, 829, 830, 831, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 927, 928, 930, 931, 932, 933, 934, 935, 936, 937, 949, 975, 976, 977, 1162, 1290, 1296, 1297, 1298, 1302, 1355, 1486, 1757, 1758, 1759, 1844, 1845, 1846, 1847, 1848, 1849, 1850, 1851, };
			
			for(Integer id : grainIdList) {
				idSet.add(id);
			}
			
			Integer foodtypeId = event.getFoodbatch().getFood().getFoodtype().getId();
			
			
			Row titleRow = sheet.createRow(0);;
			Cell titleCell1 = titleRow.createCell(1);
			titleCell1.setCellValue("名称");
			
			Cell titleCell2 = titleRow.createCell(2);
			titleCell2.setCellValue("事件主体");
			
			Cell titleCell3 = titleRow.createCell(3);
			titleCell3.setCellValue("食物名称");
			
			Cell titleCell4 = titleRow.createCell(4);
			titleCell4.setCellValue("食物类型名称");
			
			Cell titleCell5 = titleRow.createCell(5);
			titleCell5.setCellValue("发现地址");
			
			Cell titleCell6 = titleRow.createCell(6);
			titleCell6.setCellValue("发现时间");
			
			Cell titleCell7 = titleRow.createCell(7);
			titleCell7.setCellValue("来源地址");
			
			Cell titleCell8 = titleRow.createCell(8);
			titleCell8.setCellValue("来源时间");
			
			Cell titleCell9 = titleRow.createCell(9);
			titleCell9.setCellValue("事件处理");
			
			System.out.print("\\ " + event.getDescription());
			Cell titleCell10 = titleRow.createCell(10);
			titleCell10.setCellValue(event.getDescription());
			
			
			if(idSet.contains(foodtypeId)) {
				
				Row row = sheet.createRow(i++);
				
				String name = event.getName();
				String discoveryAddress = event.getDiscoveryAddress().getName();
				
				String discoveryTime = " ";
				Calendar discoveryTimea = event.getDiscoveryTime();
				if(discoveryTimea != null) {
					discoveryTime = CmiTimeUtil.getYMDString(event.getDiscoveryTime());
				}
				
				Set<Eventpunish> punishes = event.getEventpunishsForEvent();
				String eventpunishString = " "; 
				for(Eventpunish eventpunish : punishes) {
					eventpunishString = eventpunishString + eventpunish.getName();
				}
				
				Food food = event.getFoodbatch().getFood();
				Foodtype foodtype = food.getFoodtype();
				
				String sourceTime = " ";
				Calendar sTime = event.getSourceTime();
				if(sTime != null) {
					sourceTime = CmiTimeUtil.getYMDString(sTime);
				}
				String sourceAddress = event.getSourceAddress().getName();
				String subject = event.getSubject().getName();
				System.out.println();
//				System.out.print("事件名称：" + name);
//				System.out.print("事件主体：" + subject);
//				System.out.print("食物名称：" + food.getName());
//				System.out.print("食物类别：" + foodtype.getName());
//				System.out.print("发现地址：" + discoveryAddress);
//				System.out.print("发现时间：" + discoveryTime);
//				System.out.print("来源地址：" + sourceAddress);
//				System.out.print("来源时间：" + sourceTime);
//				System.out.print("处罚措施：" + eventpunishString);
//				System.out.print("事件描述：" + event.getDescription());
				
				System.out.print("\\ " + name);
				Cell cell1 = row.createCell(1);
				cell1.setCellValue(name);
				
				System.out.print("\\ " + subject);
				Cell cell2 = row.createCell(2);
				cell2.setCellValue(subject);
				
				System.out.print("\\ " + food.getName());
				Cell cell3 = row.createCell(3);
				cell3.setCellValue(food.getName());
				
				System.out.print("\\ " + foodtype.getName());
				Cell cell4 = row.createCell(4);
				cell4.setCellValue(foodtype.getName());
				
				System.out.print("\\ " + discoveryAddress);
				Cell cell5 = row.createCell(5);
				cell5.setCellValue(discoveryAddress);
				
				System.out.print("\\ " + discoveryTime);
				Cell cell6 = row.createCell(6);
				cell6.setCellValue(discoveryTime);
				
				System.out.print("\\ " + sourceAddress);
				Cell cell7 = row.createCell(7);
				cell7.setCellValue(sourceAddress);
				
				System.out.print("\\ " + sourceTime);
				Cell cell8 = row.createCell(8);
				cell8.setCellValue(sourceTime);
				
				System.out.print("\\ " + eventpunishString);
				Cell cell9 = row.createCell(9);
				cell9.setCellValue(eventpunishString);
				
				System.out.print("\\ " + event.getDescription());
				Cell cell10 = row.createCell(10);
				cell10.setCellValue(event.getDescription());
			}
	        
		}
		wb.write(fos);
        fos.close();
        wb.close();
		
	}
	
	
	@RequestMapping(value = "/frontListEchart", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void frontListEchart() throws IOException {

        String excelFileName = "E:/excel3.xlsx";//name of excel file

        String sheetName = "name";//name of sheet

        @SuppressWarnings("resource")
		XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet(sheetName) ;
        
		Set<Event> events = eventDAO.findAllEvents();
		int rowNumber = 1;
		for(Event event: events) {
			
			XSSFRow row = sheet.createRow(rowNumber);

	            //iterating c number of columns
//	            for (int c=0;c < 5; c++ ){
	                XSSFCell cell1 = row.createCell(1);

	                cell1.setCellValue(event.getId());
	                XSSFCell cell2 = row.createCell(2);
	                cell2.setCellValue(event.getName());
	                XSSFCell cell3 = row.createCell(3);
	                cell3.setCellValue(event.getFoodbatch().getFood().getFoodtype().getName());
	    			
//	    			System.out.print(event.getId() + " ");      
//	    			System.out.print("食物类别：" + event.getFoodbatch().getFood().getFoodtype().getName() + " ");
//	    			System.out.print("事件掺假类型：");
//	    			
	    			StringBuilder adultertypeSB = new StringBuilder();
	    			Set<Adultertype> adultertypes = event.getAdultertypesForEvent();
	    			for(Adultertype adultertype : adultertypes) {
	    				adultertypeSB = adultertypeSB.append(adultertype.getName()) ; 
	    			}
	    			
	    			 XSSFCell cell4 = row.createCell(4);
	    			 cell4.setCellValue(adultertypeSB.toString());
	    			
//	    			System.out.print("来源地址：" + event.getSourceAddress().getName() + " ");
	    			
	    			String time = null ;
	    			
	    			XSSFCell cell5 = row.createCell(5);
	    			if(event.getDiscoveryTime() != null) {
	    				time = event.getDiscoveryTime().get(Calendar.YEAR) + "-" + (event.getDiscoveryTime().get(Calendar.MONTH)+1) + "-" +event.getDiscoveryTime().get(Calendar.DAY_OF_MONTH);
	    			}
	    			
	    			 cell5.setCellValue(time);
	    			 
	    			 if(event.getDiscoveryAddress() != null) {
	    				 XSSFCell cell6 = row.createCell(6);
	    				 cell6.setCellValue(event.getDiscoveryAddress().getName());
	    			 }
	    			 
	    			 String punishString = null;
	    			 Set<Eventpunish> eventpunishes = event.getEventpunishsForEvent();
	    			 for(Eventpunish eventpunish :eventpunishes) {
	    				 punishString = punishString + "，" +eventpunish.getPunish().getName();
	    				 XSSFCell cell7 = row.createCell(7);
	    				 cell7.setCellValue(punishString);
	    			 }
	    			 
	    			 
	    			 Set<Foodbatchfiller> foodbatchfillers = event.getFoodbatch().getFoodbatchfillersForFoodbatch();
	    			 String fillerString = null;
//	    			 只取一个，有的冗余太多
	    			 for(Foodbatchfiller foodbatchfiller:foodbatchfillers) {
	    				 System.out.println("event的id是：" + event.getId() +  "添加剂的id是：" + foodbatchfiller.getFiller().getId() + "，名称是：" + foodbatchfiller.getFiller().getName());
	    				 if(fillerString == null) {
	    					 fillerString = foodbatchfiller.getFiller().getName();
	    				 }
	    				
	    				 XSSFCell cell8 = row.createCell(8);
	    				 cell8.setCellValue(fillerString);
	    			 }
//	            }
	            rowNumber++;
		}

        FileOutputStream fileOut = new FileOutputStream(excelFileName);

        //write this workbook to an Outputstream.
        wb.write(fileOut);
        fileOut.flush();
        fileOut.close();
        System.out.println("OK");
		
		
	
	}
	
	
	// 安卓和微信端用户调用上传报告接口，request名由filesUpload修改为submitEvent，其他的包含文件的都使用这个请求。
	//上传成功后应该返回一个合理的值
	@RequestMapping(value = "/saveEventWithFileByJson", method = RequestMethod.POST)
	@ResponseBody
	public void saveEventWithFileByJson(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletRequest request) throws IOException {
		/**
		 * 该方法还没有完成！！
		 */
		Map<String,Object> objects = new HashMap<>();
		Event event = new Gson().fromJson(multipartHttpServletRequest.getParameter("event"), Event.class);
		Food food = null;
		if (event.getParent() != null) {
			Event parentEvent = eventDAO.findEventById(event.getParent().getId());
			food = parentEvent.getFoodbatch().getFood();
		} else {
			food = event.getFoodbatch().getFood();
		}
//		通用的文件名，不同的文件在此基础上添加前缀与后缀。
		String fileName=event.getName() + "_" + String.valueOf((Long.valueOf(event.getDiscoveryTime().getTimeInMillis()) / 1000) * 1000) + "_" + UUID.randomUUID().toString();
		
		List<MultipartFile> files = multipartHttpServletRequest.getFiles("file");
		objects.put("event", event);
		objects.put("food", food);
//		保存文件到"事件上传目录"
		frontService.saveUploadFiles(files, imageUploadDirectory, "event_"+fileName);
		frontEventService.saveEntity2JsonFile(objects, eventUploadDirectory, fileName);

	}
	
//	TODO 页面端提交事件举报，这个方法暂时不处理，被submitEvent方法取代。load-video-file
	@RequestMapping(value = "/frontSaveEventWithFileByForm", method = RequestMethod.POST)
	public ModelAndView frontSaveEventWithFileByForm(@RequestParam("load-file") MultipartFile[] multipartFiles, @RequestParam("load-video-file") MultipartFile[] multipartFilesForVedio,	HttpServletRequest request) throws IOException {
		ModelAndView mav = new ModelAndView();
		
//		所有的事件的文件名都需要在页面提供的文件名后面添加事件戳+UUDI，以免数据重复冲突。
		String fileNamePostfix =(Calendar.getInstance().getTimeInMillis()) + "_" + UUID.randomUUID().toString();
//		利用文件、请求与文件后缀封装事件对象 。
		Map<String,Object> objects = frontEventService.wrapEntitys(multipartFiles,multipartFilesForVedio, request, fileNamePostfix);
		Event event = (Event)objects.get("event");
//		不带后缀名，包含路径的全 文件名，后缀名以及编号由具体的方法决定。
		String fullFileName=event.getName() + "_" + fileNamePostfix;
//		保存文件到"事件上传目录"
		
//		TODO 事件后台图片应该在这里关联，然后保存到JSON中。
		//保存图片文件
		frontService.saveUploadFiles(Arrays.asList(multipartFiles),imageUploadDirectory,"event_"+fullFileName);
		//保存视频文件
		frontService.saveUploadFiles(Arrays.asList(multipartFilesForVedio),videoUploadDirectory,"event_"+fullFileName);
		
		frontEventService.saveEntity2JsonFile(objects, eventUploadDirectory, fullFileName);
		
		mav.setViewName("front/frontPublic.jsp");
		return mav;
	}
	
// TODO　测试：因为需要从页面传到后台是对象类型的数据，而tomcat的请求参数不能有[]{}等符号，因此，修改为POST
//	如果使用集合对象，Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
	
	@RequestMapping(value = "/frontListEvents", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView frontListEvents(HttpServletRequest request, @ModelAttribute FrontEventPagination frontEventPagination) {
		ModelAndView mav = new ModelAndView();
//		TODO frontEventPaginationService中的updatePagination重构到frontEventPaginationService中
//		后台的其他也应该类似。
//		frontEventsPagination = frontEventPaginationService.updatePagination(request, frontEventsPagination);
//		每一次都查询基本食品类型是不合适的，最好的方式是在启动的时候就把前端分页的数据查找到并封装好，
//		但是，因为系统启动的时候，service和dao还没有实例化，不能调用listener或者servlet实现数据库的查询，因此，在这里使用一个判定，
//		那些需要在整个项目中列表中使用的数据采用一个单例的方式生成应该很合适
		
//		更合理的是从事件的事件
		
		int foodtypeId = -2;
		String foodtypeIdString = request.getParameter("foodtypeId");
		if(foodtypeIdString != null) {
			foodtypeId = Integer.parseInt(foodtypeIdString);
		}
		
//		TODO 把前端传递过来的食物跟类型封装到pagination中；
//		TODO 修改frontEventService的getPaginationEvents方法；
		frontEventPagination = frontEventService.updatePagination(request, frontEventPagination);
		
//		******在菜单中选中的食物类型，没有封装到pagination中，这里需要手工添加进来，不是通用的属性，因此需要手工添加进来
//		frontEventPagination.setSelectFoodtype(foodtypeDAO.findFoodtypeById(foodtypeId));
		
		Set<Event> events = frontEventService.getPaginationEvents(frontEventPagination);
		
		mav.addObject("foodtypeId", foodtypeId);//应该也可以从frontEventPagination中获取！！！
		mav.addObject("events", events);
		mav.addObject("pagination", frontEventPagination);
		mav.addObject("entityName", "event");
		mav.setViewName("front/frontListEvents.jsp");

		return mav;
	}

	

	/**
	 * 审核前端提交事件的地址
	 * @param eventJsonFile
	 * @return
	 * @throws JsonSyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/frontAuditAddress")
	public ModelAndView frontAuditAddress(@RequestParam String eventJsonFile,@RequestParam String address) throws JsonSyntaxException, IOException {
		ModelAndView mav = new ModelAndView();
		String addressJsonFile = eventJsonFile.replaceFirst("event_", address+"_");
		Gson gson = new Gson();
		AddressWrap addressWrap = new AddressWrap();
		if("discoveryAddress".equalsIgnoreCase(address)) {
			addressWrap=gson.fromJson(FileUtils.readFileToString(new File(eventUploadDirectory+"/"+addressJsonFile), "UTF-8"), AddressWrap.class);			
		}
		mav.addObject("eventJsonFile",eventJsonFile);
		mav.addObject("addressWrap",addressWrap);
		mav.setViewName("front/frontAuditAddress.jsp");
		return mav;
	}
	/**
	 * 保存通过审核的地址到数据库中
	 * @param
	 * @return
	 * @throws JsonSyntaxException
	 * @throws IOException
	 */
	@RequestMapping(value="/frontSaveAuditAddress",method = RequestMethod.POST)
	public ModelAndView frontSaveAuditAddress(@ModelAttribute AddressWrap addressWrap) throws JsonSyntaxException, IOException {
		ModelAndView mav = new ModelAndView();
		Address address = new Address();
		address.setName(addressWrap.getDetailedAddress());
		Address parentAddress = addressDAO.findAddressById(Integer.parseInt(addressWrap.getStreetId()));
		address.setParent(parentAddress);
		address.setLevel(parentAddress.getLevel()+1);
		addressService.saveAddress(address);
		mav.addObject("addressWrap",addressWrap);
		mav.setViewName("front/frontSaveAddressSuccess.jsp");
		return mav;
	}
	
	@RequestMapping(value = "/auditEvent", method = RequestMethod.GET)
//	@ResponseBody
	public ModelAndView auditEvent(@RequestParam String eventJsonFile)	throws IOException, ParseException {
		ModelAndView mav = new ModelAndView();
		System.out.println("eventJsonFile==>>"+eventJsonFile);
		Gson gson = new Gson();
		String foodJsonFile = eventJsonFile.replaceFirst("event_", "food_");
		String discoveryAddressJsonFile = eventJsonFile.replaceFirst("event_", "discoveryAddress_");
		Event event=gson.fromJson(FileUtils.readFileToString(new File(eventUploadDirectory+"/"+eventJsonFile), "UTF-8"), Event.class);
		Food food=gson.fromJson(FileUtils.readFileToString(new File(eventUploadDirectory+"/"+foodJsonFile), "UTF-8"), Food.class);
		AddressWrap discoveryAddressWrap=gson.fromJson(FileUtils.readFileToString(new File(eventUploadDirectory+"/"+discoveryAddressJsonFile), "UTF-8"), AddressWrap.class);
		
//		ArrayList<String> pictureNames = new ArrayList<String>();
//		for(Picture picture:event.getPicturesForEvent()) {
//			pictureNames.add(picture.getName());
//		}
		//EventWrap eventWrap = new EventWrap();
		//CmiAttributeUtil.copy(event, eventWrap);
		//eventWrap.setFood(food);
		
		mav.addObject("eventJsonFile",eventJsonFile);
		mav.addObject("event", event);
		mav.addObject("food", food);
		mav.addObject("discoveryAddressWrap", discoveryAddressWrap);
		mav.setViewName("eventaudit/adultEvent.jsp");
		return mav;

	}
	
	@RequestMapping(value = "/commitAuditEvent", method = RequestMethod.POST)
	public ModelAndView commitAuditEvent(@ModelAttribute Event event,HttpServletRequest request)	throws IOException, ParseException {
		System.out.println("Enter commitAuditEvent");
		
		ModelAndView mav = new ModelAndView();
		
		//地址默认支持国内地址，国外地址还不支持，且地址至少详细至街道street
		String sourceAddressParentId = request.getParameter("sourceAddressId").trim();
		String sourceAddressName = request.getParameter("sourceAddressName").trim();
		
		String discoveryAddressParentId = request.getParameter("discoveryAddressId").trim();
		String discoveryAddressName = request.getParameter("discoveryAddressName").trim();
		
		if(sourceAddressParentId!="") {
			//有详细地址，先查询详细地址是否存在，不存在则新增，存在则查找出来
			Address sourceParentAddress = addressDAO.findAddressById(Integer.parseInt(sourceAddressParentId));
			if(sourceAddressName!="") {//详细地址存在
				Address sourceAddress = addressDAO.findAddressByPhysicalPrimaryKey(sourceAddressName, Integer.parseInt(sourceAddressParentId));
				if(sourceAddress==null || sourceAddress.equals(null)) {//地址是全新地址，插入数据库
					Address source_address = new Address();
					source_address.setName(sourceAddressName);
					source_address.setLevel(sourceParentAddress.getLevel()+1);
					source_address.setParent(sourceParentAddress);
					sourceAddress = addressService.saveAddress(source_address);
				}
				event.setSourceAddress(sourceAddress);
			}else {//详细地址不存在，直接用街道代替
				event.setSourceAddress(sourceParentAddress);
			}
		}
		if(discoveryAddressParentId!="") {
			//有详细地址，先查询详细地址是否存在，不存在则新增，存在则查找出来
			Address discoveryParentAddress = addressDAO.findAddressById(Integer.parseInt(discoveryAddressParentId));
			if(discoveryAddressName!="") {//详细地址存在
				Address discoveryAddress = addressDAO.findAddressByPhysicalPrimaryKey(discoveryAddressName, Integer.parseInt(discoveryAddressParentId));
				if(discoveryAddress==null || discoveryAddress.equals(null)) {//地址是全新地址，插入数据库
					Address discovery_address = new Address();
					discovery_address.setName(discoveryAddressName);
					discovery_address.setLevel(discoveryParentAddress.getLevel()+1);
					discovery_address.setParent(discoveryParentAddress);
					discoveryAddress = addressService.saveAddress(discovery_address);
				}
				event.setDiscoveryAddress(discoveryAddress);
			}else {//详细地址不存在，直接用街道代替
				event.setDiscoveryAddress(discoveryParentAddress);
			}
		}
		/**
		 * 此处获取合格图片/视频集
		 */
		String[] qualifiedPicturesName = request.getParameterValues("pictureCheckbox");
		String[] qualifiedVideosName = request.getParameterValues("videoCheckbox");
		/**
		 * 此处获取food信息
		 */
		Food food = new Food();
		//审核人员选择的食物
		if(!request.getParameter("food").equals("")) {
			String foodId = request.getParameter("food");
			food=foodDAO.findFoodById(Integer.parseInt(foodId));
		}else {//用户在上传界面选择的食物
			if(!request.getParameter("foodId").equals("")) {
				String foodId = request.getParameter("foodId");
				food=foodDAO.findFoodById(Integer.parseInt(foodId));
				String foodName = request.getParameter("foodName").trim();
				if(foodName.equalsIgnoreCase(food.getName().trim())) {
					
				}else {//用户在事件上传界面选择的食物不正确，且数据库中没有正确的食物与之对应，审核人员只能键入食物名称
					food.setId(null);
					food.setName(foodName);
					food.setFoodtype(foodtypeDAO.findFoodtypeById(-2));
					food.setBrand(brandDAO.findBrandById(-2));
					food.setProducer(producerDAO.findProducerById(-2));
					food.setExpire(expireDAO.findExpireById(-2));
					food.setStoremethod(storemethodDAO.findStoremethodById(-2));
					food.setTaste(tasteDAO.findTasteById(-2));
					food.setProductcode(productcodeDAO.findProductcodeById(-2));
					
					food = foodService.saveFood(food);
				}
			}else {//用户在上传界面新建的食物,需要存进数据库
				String foodName = request.getParameter("foodName");
				food.setName(foodName);
				//以下7个引用字段如果不设置的话在调用saveFood()方法时会报错
				food.setFoodtype(foodtypeDAO.findFoodtypeById(-2));
				food.setBrand(brandDAO.findBrandById(-2));
				food.setProducer(producerDAO.findProducerById(-2));
				food.setExpire(expireDAO.findExpireById(-2));
				food.setStoremethod(storemethodDAO.findStoremethodById(-2));
				food.setTaste(tasteDAO.findTasteById(-2));
				food.setProductcode(productcodeDAO.findProductcodeById(-2));
				
				food = foodService.saveFood(food);
			}
		}
		
		/**
		 * 此处获取reportor信息
		 */
		User reportor = new User();
		//审核人员选择的上报者
		if(!request.getParameter("reportor").equals("")) {
			String reportorId = request.getParameter("reportor");
			reportor=userDAO.findUserById(Integer.parseInt(reportorId));
		}else {//用户在上传界面选择的reportor
			if(!request.getParameter("reportorId").equals("")) {
				String reportorId = request.getParameter("reportorId");
				reportor=userDAO.findUserById(Integer.parseInt(reportorId));
				String reportorName = request.getParameter("reportorName").trim();
				if(reportorName.equalsIgnoreCase(reportor.getName().trim())) {
					
				}else {
					reportor.setId(null);
					reportor.setName(reportorName);
					reportor.setUsername(reportorName);
					reportor.setPassword("123456");
					reportor = userService.saveUser(reportor);
				}
			}else {//用户在上传界面新建的reportor,需要存进数据库
				String reportorName = request.getParameter("reportorName");
				reportor.setName(reportorName);
				reportor.setUsername(reportorName);
				reportor.setPassword("123456");
				reportor = userService.saveUser(reportor);
			}
		}
		event.setReportor(reportor);
		/**
		 * 此处获取subject信息
		 */
		Subject subject = new Subject();
		//审核人员选择的subject
		if(!request.getParameter("subject").equals("")) {
			String subjectId = request.getParameter("subject");
			subject=subjectDAO.findSubjectById(Integer.parseInt(subjectId));
		}else {//用户在上传界面选择的subject
			if(!request.getParameter("subjectId").equals("")) {
				String subjectId = request.getParameter("subjectId");
				subject=subjectDAO.findSubjectById(Integer.parseInt(subjectId));
				String subjectName  = request.getParameter("subjectName").trim();
				if(subjectName.equalsIgnoreCase(subject.getName().trim())) {
					
				}else {
					subject.setId(null);
					subject.setName(subjectName);
					subject.setDescription(subjectName);
					subject = subjectService.saveSubject(subject);
				}
			}else {//用户在上传界面新建的subject,需要存进数据库
				String subjectName = request.getParameter("subjectName");
				subject.setName(subjectName);
				subject.setDescription(subjectName);
				subject = subjectService.saveSubject(subject);
			}
		}
		event.setSubject(subject);
		//CmiAttributeUtil.reverseCopy(event, eventWrap);
		
		String eventJsonFileName=request.getParameter("eventJsonFile");//http://localhost:8080/ema/commitAuditEvent?eventJsonFile=event_%E6%B5%8B%E8%AF%95+%E9%87%8D%E6%9E%84%E7%B3%BB%E7%BB%9F%E5%90%8EEMA%E4%BA%8B%E4%BB%B6%E7%9A%84%E6%B5%8B%E8%AF%95_1583551448000_3250b1a2-76f2-49ca-8b3c-861e61f5b621.json&name=%E6%B5%8B%E8%AF%95+%E9%87%8D%E6%9E%84%E7%B3%BB%E7%BB%9F%E5%90%8EEMA%E4%BA%8B%E4%BB%B6%E7%9A%84%E6%B5%8B%E8%AF%95&sourceTime=2020-03-08&discoveryTime=2020-03-08&auditTime=&crawlTime=2020-03-08&status=false&description=%E6%B5%8B%E8%AF%95+%E9%87%8D%E6%9E%84%E7%B3%BB%E7%BB%9F%E5%90%8EEMA%E4%BA%8B%E4%BB%B6%E7%9A%84%E6%B5%8B%E8%AF%95-%E6%8F%8F%E8%BF%B0&sourceAddress=id%3D%5Bnull%5D+name%3D%5Bnull%5D+longitude%3D%5Bnull%5D+latitude%3D%5Bnull%5D+regionalcode%3D%5Bnull%5D+postcode%3D%5Bnull%5D+prewarninglevel%3D%5Bnull%5D+description%3D%5Bnull%5D+&sourceAddress_text=&sourceAddress=&discoveryAddress=id%3D%5B28616%5D+name%3D%5B%E7%BB%87%E5%B8%83%E6%B9%BE2%E9%98%9F%5D+longitude%3D%5Bnull%5D+latitude%3D%5Bnull%5D+regionalcode%3D%5Bnull%5D+postcode%3D%5Bnull%5D+prewarninglevel%3D%5Bnull%5D+description%3D%5Bnull%5D+&discoveryAddress_text=&discoveryAddress=&subject=id%3D%5Bnull%5D+name%3D%5B%E7%B2%BE%E5%93%81%E7%B2%AE%E6%B2%B9%E5%95%86%E6%88%B7%5D+description%3D%5Bnull%5D+&subjectId=&subject_text=&subject=&auditor_text=%E6%9C%AA%E7%9F%A5&auditor=-2&uri_text=-2&uri=5239&reportor_text=%E6%9C%AA%E7%9F%A5&reportor=-2&parent=id%3D%5B-2%5D+name%3D%5B%E5%A6%82%E6%9E%9C%E8%AF%A5%E4%BA%8B%E4%BB%B6%E6%9C%AC%E6%9D%A5%E5%B0%B1%E6%98%AF%E6%A0%B9%E4%BA%8B%E4%BB%B6%EF%BC%8C%E5%B0%B1%E9%80%89%E6%8B%A9%E8%BF%99%E4%B8%80%E9%A1%B9%5D+sourceTime%3D%5Bjava.util.GregorianCalendar%5Btime%3D%3F%2CareFieldsSet%3Dfalse%2CareAllFieldsSet%3Dfalse%2Clenient%3Dtrue%2Czone%3Dsun.util.calendar.ZoneInfo%5Bid%3D%22Asia%2FShanghai%22%2Coffset%3D28800000%2CdstSavings%3D0%2CuseDaylight%3Dfalse%2Ctransitions%3D19%2ClastRule%3Dnull%5D%2CfirstDayOfWeek%3D1%2CminimalDaysInFirstWeek%3D1%2CERA%3D%3F%2CYEAR%3D1970%2CMONTH%3D0%2CWEEK_OF_YEAR%3D%3F%2CWEEK_OF_MONTH%3D%3F%2CDAY_OF_MONTH%3D1%2CDAY_OF_YEAR%3D%3F%2CDAY_OF_WEEK%3D%3F%2CDAY_OF_WEEK_IN_MONTH%3D%3F%2CAM_PM%3D0%2CHOUR%3D0%2CHOUR_OF_DAY%3D0%2CMINUTE%3D0%2CSECOND%3D0%2CMILLISECOND%3D%3F%2CZONE_OFFSET%3D%3F%2CDST_OFFSET%3D%3F%5D%5D+discoveryTime%3D%5Bjava.util.GregorianCalendar%5Btime%3D%3F%2CareFieldsSet%3Dfalse%2CareAllFieldsSet%3Dfalse%2Clenient%3Dtrue%2Czone%3Dsun.util.calendar.ZoneInfo%5Bid%3D%22Asia%2FShanghai%22%2Coffset%3D28800000%2CdstSavings%3D0%2CuseDaylight%3Dfalse%2Ctransitions%3D19%2ClastRule%3Dnull%5D%2CfirstDayOfWeek%3D1%2CminimalDaysInFirstWeek%3D1%2CERA%3D%3F%2CYEAR%3D1970%2CMONTH%3D0%2CWEEK_OF_YEAR%3D%3F%2CWEEK_OF_MONTH%3D%3F%2CDAY_OF_MONTH%3D1%2CDAY_OF_YEAR%3D%3F%2CDAY_OF_WEEK%3D%3F%2CDAY_OF_WEEK_IN_MONTH%3D%3F%2CAM_PM%3D0%2CHOUR%3D0%2CHOUR_OF_DAY%3D0%2CMINUTE%3D0%2CSECOND%3D0%2CMILLISECOND%3D%3F%2CZONE_OFFSET%3D%3F%2CDST_OFFSET%3D%3F%5D%5D+auditTime%3D%5Bjava.util.GregorianCalendar%5Btime%3D%3F%2CareFieldsSet%3Dfalse%2CareAllFieldsSet%3Dfalse%2Clenient%3Dtrue%2Czone%3Dsun.util.calendar.ZoneInfo%5Bid%3D%22Asia%2FShanghai%22%2Coffset%3D28800000%2CdstSavings%3D0%2CuseDaylight%3Dfalse%2Ctransitions%3D19%2ClastRule%3Dnull%5D%2CfirstDayOfWeek%3D1%2CminimalDaysInFirstWeek%3D1%2CERA%3D%3F%2CYEAR%3D1970%2CMONTH%3D0%2CWEEK_OF_YEAR%3D%3F%2CWEEK_OF_MONTH%3D%3F%2CDAY_OF_MONTH%3D1%2CDAY_OF_YEAR%3D%3F%2CDAY_OF_WEEK%3D%3F%2CDAY_OF_WEEK_IN_MONTH%3D%3F%2CAM_PM%3D0%2CHOUR%3D0%2CHOUR_OF_DAY%3D0%2CMINUTE%3D0%2CSECOND%3D0%2CMILLISECOND%3D%3F%2CZONE_OFFSET%3D%3F%2CDST_OFFSET%3D%3F%5D%5D+crawlTime%3D%5Bjava.util.GregorianCalendar%5Btime%3D%3F%2CareFieldsSet%3Dfalse%2CareAllFieldsSet%3Dfalse%2Clenient%3Dtrue%2Czone%3Dsun.util.calendar.ZoneInfo%5Bid%3D%22Asia%2FShanghai%22%2Coffset%3D28800000%2CdstSavings%3D0%2CuseDaylight%3Dfalse%2Ctransitions%3D19%2ClastRule%3Dnull%5D%2CfirstDayOfWeek%3D1%2CminimalDaysInFirstWeek%3D1%2CERA%3D%3F%2CYEAR%3D1970%2CMONTH%3D0%2CWEEK_OF_YEAR%3D%3F%2CWEEK_OF_MONTH%3D%3F%2CDAY_OF_MONTH%3D1%2CDAY_OF_YEAR%3D%3F%2CDAY_OF_WEEK%3D%3F%2CDAY_OF_WEEK_IN_MONTH%3D%3F%2CAM_PM%3D0%2CHOUR%3D0%2CHOUR_OF_DAY%3D0%2CMINUTE%3D0%2CSECOND%3D0%2CMILLISECOND%3D%3F%2CZONE_OFFSET%3D%3F%2CDST_OFFSET%3D%3F%5D%5D+status%3D%5Bfalse%5D+description%3D%5B%E6%9C%AA%E7%9F%A5%5D+&parentId=&parent_text=&parent=&foodbatch_text=%E6%9C%AA%E7%9F%A5&foodbatch=68&eventsForParent_text=&eventsForParent=-2&adultertypesForEvent_text=&adultertypesForEvent=-2&motivesForEvent_text=&motivesForEvent=-2&eventadulterlinksForEvent_text=&eventadulterlinksForEvent=-2&eventpunishsForEvent_text=&eventpunishsForEvent=-2&eventqualitytypesForEvent_text=&eventqualitytypesForEvent=-2&eventquantitytypesForEvent_text=&eventquantitytypesForEvent=-2&picturesForEvent_text=&picturesForEvent=61216&videosForEvent_text=&videosForEvent=%5B%5D&fileName=   request.getParameter("eventJsonFile");
		//首先保存关联数据
		Event parent = event.getParent();
//		User reportor = event.getReportor();
//		Subject subject = event.getSubject();
		Address discoveryAddress = event.getDiscoveryAddress();
		Address sourceAddress = event.getSourceAddress();
		//event的parent从上传事件那边的代码可知parent一定在数据库中，要么未知id==-2，要么已知
		//因此此处不必再次查询数据库
//		if(!parent.equals(null)) {
//			parent = eventService.saveEvent(parent);
//			event.setParent(parent);
//		}
		//前台传过来的parent数据不完整，应该在数据库中通过id找出parent在setter
		//parent未知或者parent没有填写留空时默认parent为-2
		if(parent.getName()=="未知" || parent.getName().length()==0 || parent.getId()==-2) {
			event.setParent(eventService.findEventByPrimaryKey(-2));
		}else {
			event.setParent(eventService.findEventByPrimaryKey(parent.getId()));
		}
		
		//subject、discoveryAddress、sourceAddress可直接再页面修改，因此可能是新增的数据条目，应当在数据库进行查重
		/**
		 * 数据库设计中event的subject字段不为null，前端页面应该做空检查
		 */
//		if(!subject.getId().equals(null)) {
//			//把id设置为null，强制后台通过物理主键进行查重，物理主键查重可能有问题，因为物理主键字段可能为空，getName或者getId时可能报错
//			//subject.setId(null);
//			//subject = subjectService.saveSubject(subject);
//			event.setSubject(subjectDAO.findSubjectById(subject.getId()));
//		}else{
//			subject = subjectService.saveSubject(subject);
//			event.setSubject(subject);
//		}
		/**
		 * 保存reportor
		 */
//		if(!reportor.getId().equals(null)) {
//			//把id设置为null，强制后台通过物理主键进行查重，物理主键查重可能有问题，因为物理主键字段可能为空，getName或者getId时可能报错
//			//reportor.setId(null);
//			
//			event.setReportor(userDAO.findUserById(reportor.getId()));
//		}else {
//			/**
//			 * 默认值并没有意义，应该在审核页面强制审核人员在数据库进行选择
//			 */
//			reportor.setUsername(reportor.getName());
//			reportor.setPassword("123456");
//			reportor = userService.saveUser(reportor);
//			event.setReportor(reportor);
//		}
		
		System.out.println("discoveryAddress==>>"+discoveryAddress);
		/**
		 * 保存地址至少要满足三个字段不为空，即name、parent、prewarninglevel
		 */
		//地址肯定是在审核页面已经存进数据库了，此处的地址要么为null要么具有id
//		if(!discoveryAddress.getId().equals(null)) {//地址如果没有name，则认为地址为null
//			//discoveryAddress.setParent(addressService.findAddressByPrimaryKey(discoveryAddress.getId()));
//			//默认地址是新增的，数据库中不存在，强制后台进行查重处理
//			//discoveryAddress.setId(null);
//			event.setDiscoveryAddress(addressDAO.findAddressById(discoveryAddress.getId()));
//		}else {
//			event.setDiscoveryAddress(null);
//		}
		System.out.println("sourceAddress==>>"+sourceAddress);
		//sourceAddress如果不填，name默认为""，也就是empty，所以要加空检查
		/**
		 * 保存地址至少要满足三个字段不为空，即name、parent、prewarninglevel
		 */
//		if(!sourceAddress.getId().equals(null)) {
//			//System.out.println("进入sourceAddress");
//			//sourceAddress.setParent(addressService.findAddressByPrimaryKey(sourceAddress.getId()));
//			//sourceAddress.setId(null);
//			//sourceAddress = addressService.saveAddress(sourceAddress);
//			event.setSourceAddress(addressDAO.findAddressById(sourceAddress.getId()));
//		}else {
//			event.setSourceAddress(null);
//		}
		//这里先保存event，因为保存图片时需要用到event
		System.out.println("保存event之前");
		event = eventService.saveEvent(event);
		System.out.println("保存event之后");
//		移除event.json文件、food.json文件，图片文件；
		File eventJsonFile=new File(eventUploadDirectory+"/"+eventJsonFileName);
		File foodJsonFile=new File(eventUploadDirectory+"/"+eventJsonFileName.replaceFirst("event_", "food_"));
		File discoveryAddressJsonFile=new File(eventUploadDirectory+"/"+eventJsonFileName.replaceFirst("event_", "discoveryAddress_"));
		
		File pictureDirectory = new File(imageUploadDirectory);
		File videoDirectory = new File(videoUploadDirectory);
		/**
		 * 移动图片：
		 * 1、将审核通过的图片移动到已经审核文件夹
		 * 2、将审核不通过的图片移动到不合格文件夹imageUnqualifiedDirectory
		 */
		String[] pictureNames = pictureDirectory.list();
		String[] videoNames = videoDirectory.list();
		for(int i=0;i<pictureNames.length;i++) {
			//属于该事件的相关图片
			if(pictureNames[i].contains(eventJsonFileName.replaceAll(".json", ""))) {
				boolean flag = false;
				//图片是否通过审核
				for(String picName:qualifiedPicturesName) {
					if(picName.equalsIgnoreCase(pictureNames[i])) {
						flag=true;
						break;
					}
				}
				if(flag) {
					//通过审核，移动图片到已审核目录，并将图片信息保存进数据库
					Picture picture = new Picture();
					picture.setName(pictureNames[i]);
					picture.setPath(pictureNames[i]);
					picture.setEvent(event);
					picture.setFood(food);
					pictureService.savePicture(picture);
					FileUtils.moveFileToDirectory(new File(imageUploadDirectory+"/"+pictureNames[i]), new File(imageAdultDirectory),false);
				}else {
					//未通过审核，移动图片到不合格图片目录，不需保存图片信息到数据库
					FileUtils.moveFileToDirectory(new File(imageUploadDirectory+"/"+pictureNames[i]), new File(imageUnqualifiedDirectory),false);
				}
				
			}
		}

		for(int i=0;i<videoNames.length;i++) {
			//属于该事件的相关视频
			if(videoNames[i].contains(eventJsonFileName.replaceAll(".json", ""))) {
				boolean flag = false;
				//视频是否通过审核
				//把qualifiedVideosName转换成ArrayList会更好简化逻辑
				for(String vdoName:qualifiedVideosName) {
					if(vdoName.equalsIgnoreCase(videoNames[i])) {
						flag=true;
						break;
					}
				}
				if(flag) {
					//通过审核，移动视频到已审核目录，并将视频信息保存进数据库
					Video video = new Video();
					video.setName(videoNames[i]);
					video.setPath(videoNames[i]);
					video.setEvent(event);
					video.setFood(food);
					videoService.saveVideo(video);
					FileUtils.moveFileToDirectory(new File(videoUploadDirectory+"/"+videoNames[i]), new File(videoAdultDirectory),false);
				}else {
					//未通过审核，移动视频到不合格视频目录，不需保存视频信息到数据库
					FileUtils.moveFileToDirectory(new File(videoUploadDirectory+"/"+videoNames[i]), new File(videoUnqualifiedDirectory),false);
				}
				
			}
		}
		
//		移动事件的event.json和food.json文件 。
		FileUtils.moveFileToDirectory(eventJsonFile, new File(eventAdultDirectory), false);
		FileUtils.moveFileToDirectory(foodJsonFile, new File(eventAdultDirectory), false);
		FileUtils.moveFileToDirectory(discoveryAddressJsonFile, new File(eventAdultDirectory), false);
		mav.addObject("event", event);
		mav.setViewName("eventaudit/listUserEvent4Audit.jsp");
		return mav;
	}
		

	@RequestMapping(value = "/toAuditEvent", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> toAuditEvent(@RequestParam(value = "fileName") String fileName) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();

		Event event = new Event();
		StringBuffer eventName = new StringBuffer();
		eventName.append(eventUploadDirectory);
		eventName.append("/" + fileName);
		File file = new File(eventName.toString());
		Gson gson = new Gson();
		Food food = new Food();
		Foodbatch foodbatch = new Foodbatch();
		Unit unit = new Unit();
		unit = unitDAO.findUnitById(-2);

		String[] spilt = fileName.split("event");
		StringBuffer foodPath = new StringBuffer().append(eventUploadDirectory).append("/").append("food")
				.append(spilt[1]);
		event = gson.fromJson(FileUtils.readFileToString(new File(eventName.toString()), "UTF-8"), Event.class);
		food = gson.fromJson(FileUtils.readFileToString(new File(foodPath.toString()), "UTF-8"), Food.class);
		foodbatch.setFood(food);
		foodbatch.setName(event.getName());
		foodbatch.setBatch("未知");
		foodbatch.setUnit(unit);
		foodbatch.setDate(event.getDiscoveryTime());
		event.setFoodbatch(foodbatch);
		event.setSourceAddress(event.getParent().getSourceAddress());
		event.setAuditor(userDAO.findUserById(-2));
		event.setUrl(urlDAO.findUrlById(-2));
		event.setReportor(userDAO.findUserById(-2));

		if (food.getId() == null) {
			food.setBrand(brandDAO.findBrandById(-2));
			food.setExpire(expireDAO.findExpireById(-2));
			food.setStoremethod(storemethodDAO.findStoremethodById(-2));
			food.setFoodtype(foodtypeDAO.findFoodtypeById(-2));
			food.setProductcode(productcodeDAO.findProductcodeById(-2));
			food.setProducer(producerDAO.findProducerById(-2));
			food.setTaste(tasteDAO.findTasteById(-2));
			food = foodService.saveFood(food);
			foodbatch.setFood(food);// 保存食物
		}
		foodbatch = foodbatchService.saveFoodbatch(foodbatch);// 保存foodbatch
		event.setFoodbatch(foodbatch);
		if (event.getSubject().getId() == null) {
			event.setSubject(subjectService.saveSubject(event.getSubject()));
		}
		event.setSourceAddress(event.getDiscoveryAddress());
		// 返回一整个Event不行，只能分开
		map.put("eventName", event.getName());
		map.put("parentId", event.getDiscoveryAddress().getId());
		// 这里可以根据parentId返回所有的上级节点的地址
		map.put("subject", event.getSubject().getName());
		map.put("parent", event.getParent().getName());
		map.put("description", event.getDescription());
		map.put("reporterId", event.getReportor().getId());
		map.put("discoveryTime", event.getDiscoveryTime());
		map.put("parentName", event.getParent().getName());
		map.put("parentId", event.getParent().getId());
		map.put("subjectName", event.getSubject().getName());
		map.put("subjectId", event.getSubject().getId());
		map.put("fileName", fileName);
		map.put("discoveryAddressName", event.getDiscoveryAddress().getName());
		map.put("discoveryAddressId", event.getDiscoveryAddress().getId());
//		map.put("sourceAddress", event.getSourceAddress().getName());数据库的所有事件的源地址为空，待解决？
		return map;
	}

	
	
	@RequestMapping("/auditAllEventsOneByOne")
	public ModelAndView auditAllEventsOneByOne(@ModelAttribute Event event, HttpServletRequest request) throws IOException {
		
//		status是0，表示没有审核。是1表示已经审核了。
//		把编辑event.jsp的页面修改一下，
		ModelAndView mav = new ModelAndView();
		
		String save = request.getParameter("save");
		String delete = request.getParameter("delete");
		String pass = request.getParameter("pass");
		
		
		
		if(save != null) {
			event.setStatus(true);
		}
		
		if(delete != null) {
			event.setStatus(false);
		}
		
		if(pass != null) {
			event.setStatus(null);
		}
		
		
		
//		save， delete, pass不都等于null，表示是需要处理的数据。
		if(!(save == null && delete == null && pass == null)) {
			//（1）删除
			if(event.getStatus() == false) {
//				应该都是空，然后保存，然后删除
//				因为status只设置了1位，删除的时候又又级联删除的问题，暂时设置description为“该事件经过审核是无效事件，待后期清理”
				event.setDescription(toBeDeleteEventDescription );
				event.setStatus(false);
				event = eventService.saveEvent(event);
			}else {//（2）更新或者设置为不处理
				Address sourceAddressTemp = event.getSourceAddress();
				Address sourceAddress = sourceAddressTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(addressDAO.findAddressById(sourceAddressTemp.getId()));
				Address discoveryAddressTemp = event.getDiscoveryAddress();
				Address discoveryAddress = discoveryAddressTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(addressDAO.findAddressById(discoveryAddressTemp.getId()));
				Subject subjectTemp = event.getSubject();
				Subject subject = subjectTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(subjectDAO.findSubjectById(subjectTemp.getId()));
				User auditorTemp = event.getAuditor();
				User auditor = auditorTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(userDAO.findUserById(auditorTemp.getId()));
				Url uriTemp = event.getUrl();
				Url uri = uriTemp == null ? null : CmiHibernateProxyUtil.deproxy(urlDAO.findUrlById(uriTemp.getId()));
				User reportorTemp = event.getReportor();
				User reportor = reportorTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(userDAO.findUserById(reportorTemp.getId()));
				Event parentTemp = event.getParent();
				Event parent = parentTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(eventDAO.findEventById(parentTemp.getId()));
				Foodbatch foodbatchTemp = event.getFoodbatch();
				Foodbatch foodbatch = foodbatchTemp == null ? null
						: CmiHibernateProxyUtil.deproxy(foodbatchDAO.findFoodbatchById(foodbatchTemp.getId()));

				event.setSourceAddress(sourceAddress);
				event.setDiscoveryAddress(discoveryAddress);
				event.setSubject(subject);
				event.setAuditor(auditor);
				event.setUrl(uri);
				event.setReportor(reportor);
				event.setParent(parent);
				event.setFoodbatch(foodbatch);
				
				event.setAuditTime(Calendar.getInstance());
				eventService.saveEvent(event);//如果状态不是false，表示就是审核通过或者暂时不处理。删除，
			}
		}
		
		
//		不管是不是需要处理数据，都修要重新获取最新的没有处理的数据。
//		第二部分：将数据保存后再获取新的数据		
		Set<Event> events = cmiEventDAO.findEventByStatusAndDescription(false, toBeDeleteEventDescription, -1, 1);
		event =  CmiSetUtil.getSoleInstance(events);

		mav.addObject("event", event);

		// 把所有的引用event对象都添加到mav对象，供前台页面选择
		if(event !=null) {
			mav.addAllObjects(eventService.loadEventObjectReferencedSet(event));
		}
		
		mav.setViewName("eventaudit/auditAllEventsOneByOne.jsp");
		return mav;
	}
	
	
	@RequestMapping("/listUserEvent4Audit")
	public ModelAndView listUserEvent4Audit() throws IOException {

		ModelAndView mav = new ModelAndView();
		List<Event> eventList = new ArrayList<Event>();
		List<Food> foodList = new ArrayList<Food>();
		//List<Address4Adapter> discoveryAddressList = new ArrayList<Address4Adapter>();
		List<String> jsonFileList = new ArrayList<String>();
		List<String> pictuerList = new ArrayList<String>();
		Gson gson = new Gson();
//		上传的文件目录
		File[] jsonFiles =(new File(eventUploadDirectory)).listFiles();
//		TODO  暂时待定
//		pictureCountList.add(count);
		ArrayList<File> foodFiles = new ArrayList<>();
		ArrayList<File> eventFiles = new ArrayList<>();
		ArrayList<File> discoveryAddressFiles = new ArrayList<>();
		for(File file:jsonFiles) {
			if(file.getName().startsWith("event")) {
				eventFiles.add(file);
			}else if(file.getName().startsWith("food")){
				foodFiles.add(file);
			}else {
				discoveryAddressFiles.add(file);//暂时用不到
			}
		}
//		event_测试 重构系统后EMA事件的测试_1583550213000_ac784b94-0042-471c-a965-7b1684594587.json		
//		event_测试 重构系统后EMA事件的测试_1583551448000_3250b1a2-76f2-49ca-8b3c-861e61f5b621_0.jpg
		Event event=null;
		Food food = null;
		AddressWrap discoveryAddress =null;
		String eventFileName = null;
		//此处还可以简化，简化方法见注释【简化】
		for(File f:eventFiles) {
			eventFileName = f.getName();
			for(File fi:foodFiles) {
				if(eventFileName.replaceFirst("event_", "food_").equalsIgnoreCase(fi.getName())) {
					event=gson.fromJson(FileUtils.readFileToString(f, "UTF-8"), Event.class);
					food = gson.fromJson(FileUtils.readFileToString(fi, "UTF-8"), Food.class);
					//注释：==>>【简化】,可以免去循环
					discoveryAddress = gson.fromJson(FileUtils.readFileToString(new File(eventUploadDirectory+"/"+eventFileName.replaceFirst("event_", "discoveryAddress_")), "UTF-8"), AddressWrap.class);
					event.getDiscoveryAddress().setName(discoveryAddress.getCountry()+discoveryAddress.getProvince()+
							discoveryAddress.getCity()+discoveryAddress.getArea()+
							discoveryAddress.getStreet()+discoveryAddress.getDetailedAddress());;
					eventList.add(event);
					foodList.add(food);
					for(Picture pic:event.getPicturesForEvent()) {
						pictuerList.add(pic.getPath());
						System.out.println("Path==>>"+pic.getPath());
						break;
						
					}
					jsonFileList.add(f.getName());
				}
			}
		}
//		for (int i = 0; i < jsonFiles.length; i++) {
//			String fileName = jsonFiles[i].getName();
//			if (fileName.startsWith("event")) {
//				Event event=gson.fromJson(FileUtils.readFileToString(jsonFiles[i], "UTF-8"), Event.class);
//				eventsList.add(event);
//				for(Picture pic:event.getPicturesForEvent()) {
//					pictuersList.add(pic.getPath());
//					System.out.println("Path==>>"+pic.getPath());
//					break;
//					
//				}
//				jsonFileList.add(jsonFiles[i].getName());
////				food = gson.fromJson(FileUtils.readFileToString(new File(foodPath.toString()), "UTF-8"), Food.class);
//			}
//		}
		mav.addObject("eventList", eventList);
		mav.addObject("entityName", "event");
		mav.addObject("foodList", foodList);
		mav.addObject("pictuerList", pictuerList);
		mav.addObject("jsonFileList", jsonFileList);
		mav.setViewName("eventaudit/listUserEvent4Audit.jsp");
		return mav;
	}

	@RequestMapping("/listCrawlEvent4Audit")
	public ModelAndView listCrawlEvent4Audit() throws IOException {
		// 爬虫爬取的图片没保存，无法显示
		ModelAndView mav = new ModelAndView();
		List<Event> eventsList = new ArrayList<Event>();
		List<String> pictuersList = new ArrayList<String>();
		List<String> discoveryTimesList = new ArrayList<String>();

		Event event = new Event();
		Gson gson = new Gson();
		String discoveryTime = null;
		String pictuerPath = null;
		File jsonfile = new File(eventAdultDirectory);
		File[] files = jsonfile.listFiles();

		for (int i = 0; i < files.length; i++) {
			InputStream inputStream = new FileInputStream(files[i]);
			String line = null;
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			line = reader.readLine();
			event = gson.fromJson(line, Event.class);
			eventsList.add(event);
			discoveryTime = String.valueOf(event.getDiscoveryTime().getTimeInMillis());
			discoveryTimesList.add(discoveryTime);
//				pictuerPath = "/" + event.getName() + discoveryTime + "/" + event.getName() + discoveryTime + "0.png";
//				pictuersList.add(pictuerPath);
			reader.close();
		}

		mav.addObject("eventsList", eventsList);
		mav.addObject("pictuersList", pictuersList);
		mav.addObject("discoveryTimesList", discoveryTimesList);
		mav.setViewName("eventaudit/listCrawlEvent4Audit.jsp");
		return mav;
	}

}